package generator;

import generator.util.FileHelper;
import org.apache.commons.io.FileUtils;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author badqiu
 * @email badqiu(a)gmail.com
 */
public class Generator {
    private static final String WEBAPP_GENERATOR_INSERT_LOCATION = "webapp-generator-insert-location";
    //	private static final String WEBAPP_GENERATOR_INSERT_BEFORE_LOCATION = WEBAPP_GENERATOR_INSERT_LOCATION+":before";
//	private static final String WEBAPP_GENERATOR_INSERT_AFTER_LOCATION = WEBAPP_GENERATOR_INSERT_LOCATION+":after";
    private Map cf;

    public Generator(Map cf) {
        this.cf = cf;
    }


    //生成工程
    public void generateProject() throws Exception {
        System.out.println("***************************************************************");
        System.out.println("* BEGIN generate project;");
        System.out.println("***************************************************************");
        //获取resources目录
        File rootDir = new File(this.getClass().getClassLoader().getResource("template").getFile()).getAbsoluteFile();
        //获取目录下所有的文件和文件夹
        List files = new ArrayList();
        FileHelper.listFiles(rootDir, files);

        for (int i = 0; i < files.size(); i++) {
            File file = (File) files.get(i);
            String templateRelativePath = FileHelper.getRelativePath(rootDir, file);

            //过滤一些不必要的文件
            if (file.isDirectory() || file.isHidden())
                continue;
            if (templateRelativePath.trim().equals(""))
                continue;
            if (file.getName().toLowerCase().endsWith(".include")) {
                continue;
            }
            try {
                //获取生成项目的根目录
                String outRoot = getOutRootDir();
                //对源文件路径进行格式化
                templateRelativePath = FreemarkerMapper.formartStr(templateRelativePath, cf).toString();
                //获取生成文件file对象
                File outputFile = new File(outRoot, templateRelativePath);
                //创建file的所有父目录
                outputFile.getParentFile().mkdirs();
                //获取file中的文本内容
                String resource = FileUtils.readFileToString(file);
                //对文本内容格式化
                StringWriter result = FreemarkerMapper.formartStr(resource, cf);
                //写入到目标文件中
                FileUtils.writeStringToFile(outputFile, result.toString());
                System.out.println(outputFile.toURI()+" generate success!");
            } catch (Exception e) {
                throw new RuntimeException("file ==>" + templateRelativePath + " generate error!", e);
            }
        }

    }


    public void clean() throws IOException {
        String outRoot = getOutRootDir();
        FileUtils.deleteDirectory(new File(outRoot));
    }

    private String getOutRootDir() {
        return (String) this.cf.get("outRoot");
    }

}
